package com.ssyt.hiring.common;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ssyt.hiring.common.util.FastjsonUtil;
import com.ssyt.hiring.talent.service.TalentService;

public class CommonServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	private CommonService commonService = new CommonService();
	private TalentService talentService = new TalentService();

	public CommonServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding(Constants.ENCODE_UTF8);
		String command = request.getParameter("command");
		if ("toForgetPasswordUI".equals(command)) {
			toForgetPasswordUI(request, response);
		} else if ("sendEmail".equals(command)) {
			sendEmail(request, response);
		} else if ("toUpdatePasswordUI".equals(command)) {
			toUpdatePasswordUI(request, response);
		} else if ("updatePassword".equals(command)) {
			updatePassword(request, response);
		} else if ("listAreaInfo".equals(command)) {
			listAreaInfo(request, response);
		} else if ("listCityByProvinceId".equals(command)) {
			listCityByProvinceId(request, response);
		} else if ("loadingData".equals(command)) {
			loadingData(request, response);
		}
	}

	/**
	 * 转到找回密码页面
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void toForgetPasswordUI(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.getRequestDispatcher("/WEB-INF/view/common/forget-password.jsp")
				.forward(request, response);
	}

	/**
	 * 发送密码重置邮件
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void sendEmail(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String accountType = request.getParameter("accountType");
		String email = request.getParameter("email");
		String validateCode = request.getParameter("validateCode");
		String sessionValidateCode = (String) request.getSession()
				.getAttribute(
						com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
		// 1、验证码判断
		if (validateCode.equals(sessionValidateCode)) {
			// 2、检查邮箱在数据库里是否存在
			boolean result = talentService.isExistEmail(accountType, email);
			if (result) {
				// 3、如果验证码正确，再执行邮件的发送
				boolean sendResult = commonService.send(email, accountType);
				if (sendResult) {
					request.setAttribute("msg", "邮件已发送到邮箱，请查看！");
					request.getRequestDispatcher(
							"/WEB-INF/view/talent/login.jsp").forward(request,
							response);
				} else {
					request.setAttribute("msg", "邮件发送失败！");
					toForgetPasswordUI(request, response);
				}
			} else {
				request.setAttribute("msg", "没有此邮箱地址！");
				toForgetPasswordUI(request, response);
			}
		} else {
			request.setAttribute("msg", "验证码输入错误！");
			request.setAttribute("email", email);
			toForgetPasswordUI(request, response);
		}
	}

	/**
	 * 转到修改密码页面
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void toUpdatePasswordUI(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// 判断此次链接请求是否已过期
		String accountType = request.getParameter("accountType");
		String email = request.getParameter("email");
		boolean result = talentService.isEmailLinkExpired(email, accountType);
		if (result) {
			request.getRequestDispatcher(
					"/WEB-INF/view/common/update-password-fail.jsp").forward(
					request, response);
		} else {
			// 如果没有过期，还要判断邮箱和密钥是否匹配
			String securityKey = request.getParameter("securityKey");
			boolean matchedResult = talentService.isMatched(email, accountType,
					securityKey);
			if (matchedResult) {
				request.getRequestDispatcher(
						"/WEB-INF/view/common/update-password.jsp").forward(
						request, response);
			} else {
				request.getRequestDispatcher(
						"/WEB-INF/view/common/update-password-fail.jsp")
						.forward(request, response);
			}
		}
	}

	/**
	 * 修改密码页面
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void updatePassword(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String accountType = request.getParameter("accountType");
		String email = request.getParameter("email");
		String newPassword = request.getParameter("newPassword");
		talentService.updatePassword(accountType, email, newPassword);
		request.getRequestDispatcher("/WEB-INF/view/talent/login.jsp").forward(
				request, response);
	}

	/**
	 * 默认显示的城市信息
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void listAreaInfo(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		List<Province> provinceList = commonService.listAllProvince();
		List<City> cityList = commonService.listCityByProvinceId("500000");
		List<Area> areaList = commonService.listAreaByCityId("500100");

		request.setAttribute("provinceListStr",
				FastjsonUtil.toJson(provinceList));
		request.setAttribute("cityListStr", FastjsonUtil.toJson(cityList));
		request.setAttribute("areaListStr", FastjsonUtil.toJson(areaList));
		request.getRequestDispatcher("/WEB-INF/view/common/area.jsp").forward(
				request, response);
	}

	/**
	 * 根据ProvinceId查询对应City
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void listCityByProvinceId(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String provinceId = request.getParameter("provinceId");

		List<City> cityList = commonService.listCityByProvinceId(provinceId);
		List<Area> areaList = commonService.listAreaByCityId(cityList.get(0)
				.getCityId());
		List<Object> datas = new ArrayList<>();
		datas.add(cityList);
		datas.add(areaList);

		// 把文本打印给页面，但要确定编码，访问中文乱码
		response.setContentType("text/html; charset=UTF-8");
		response.getWriter().print(FastjsonUtil.toJson(datas));
	}

	/**
	 * 加载一批数据
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private class Info {
		private String companyName;
		private String slogan;
		private String positionName;
		private int salary1;
		private int salary2;
		private String address;

		public Info() {
			super();
		}

		public Info(String companyName, String slogan, String positionName,
				int salary1, int salary2, String address) {
			super();
			this.companyName = companyName;
			this.slogan = slogan;
			this.positionName = positionName;
			this.salary1 = salary1;
			this.salary2 = salary2;
			this.address = address;
		}

		public String getCompanyName() {
			return companyName;
		}

		public void setCompanyName(String companyName) {
			this.companyName = companyName;
		}

		public String getSlogan() {
			return slogan;
		}

		public void setSlogan(String slogan) {
			this.slogan = slogan;
		}

		public String getPositionName() {
			return positionName;
		}

		public void setPositionName(String positionName) {
			this.positionName = positionName;
		}

		public int getSalary1() {
			return salary1;
		}

		public void setSalary1(int salary1) {
			this.salary1 = salary1;
		}

		public int getSalary2() {
			return salary2;
		}

		public void setSalary2(int salary2) {
			this.salary2 = salary2;
		}

		public String getAddress() {
			return address;
		}

		public void setAddress(String address) {
			this.address = address;
		}

	}

	private void loadingData(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		List<Info> list = new ArrayList<>();
		for (int i = 0; i < 10; i++) {
			Info info = new Info("上善云图" + i, "没有口号" + i, "Java开发工程师" + i, 1,
					1000, "重庆" + i);
			list.add(info);
		}

		// 把文本打印给页面，但要确定编码，访问中文乱码
		response.setContentType("text/html; charset=UTF-8");
		response.getWriter().print(FastjsonUtil.toJson(list));
	}
}
